package com.cf.base.mvp.mvp;

import com.cf.base.mvp.callback.PresenterLifecycleCallbacks;
import com.cf.base.mvp.log.LogUtils;
import com.cf.base.mvp.log.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangji
 */
public class Mvp {

    private Logger log;

    private PresenterLifecycleCallbacks presenterManager = new PresenterLifecycleCallbacks() {
        @Override
        public void onCreate(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onCreate(presenter));
        }

        @Override
        public void onStart(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onStart(presenter));
        }

        @Override
        public void onResume(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onResume(presenter));
        }

        @Override
        public void onPause(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onPause(presenter));
        }

        @Override
        public void onStop(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onStop(presenter));
        }

        @Override
        public void onDestroy(IPresenter presenter) {
            mCallback.forEach(callbacks -> callbacks.onDestroy(presenter));
        }
    };

    private List<PresenterLifecycleCallbacks> mCallback;

    private static Mvp instance;

    public static Mvp getInstance() {
        if (instance == null) {
            synchronized (Mvp.class) {
                if (instance == null) {
                    instance = new Mvp();
                }
            }
        }
        return instance;
    }

    private Mvp() {
        mCallback = new ArrayList<>();
    }

    public void registerPresenterLifecycleCallbacks(PresenterLifecycleCallbacks callback) {
        mCallback.add(callback);
    }

    public void unRegisterPresenterLifecycleCallbacks(PresenterLifecycleCallbacks callback) {
        mCallback.remove(callback);
    }

    public PresenterLifecycleCallbacks getPresenterManager() {
        return presenterManager;
    }

    public Logger getLog() {
        return log == null ? new Logger.Default() : log;
    }

    public void setLog(Logger log) {
        this.log = log;
    }
}
